<template>
  <div class="app-container" :class="{ 'login-layout': isLoginPage }">
    <!-- 登录页面使用独立布局 -->
    <template v-if="isLoginPage">
      <router-view />
    </template>

    <!-- 其他页面使用带侧边栏的布局 -->
    <template v-else>
      <!-- 移动端菜单按钮 -->
      <button class="mobile-menu-btn" @click="toggleMobileMenu" aria-label="切换菜单">
        <span class="hamburger-icon">
          <span></span>
          <span></span>
          <span></span>
        </span>
      </button>

      <!-- 遮罩层 -->
      <div 
        class="mobile-overlay" 
        :class="{ 'active': isMobileMenuOpen }"
        @click="closeMobileMenu"
      ></div>

      <!-- 左侧导航栏 -->
      <aside class="app-sidebar" :class="{ 'mobile-open': isMobileMenuOpen }">
        <div class="sidebar-header">
          <h1 class="logo">
            <i class="icon">📝</i>
            创作中心
          </h1>
        </div>

        <nav class="sidebar-nav">
          <!-- 动态菜单 -->
          <template v-if="userMenus.length > 0">
            <router-link
              v-for="menu in userMenus"
              :key="menu.id"
              :to="menu.path"
              class="nav-item"
              active-class="active"
            >
              <i class="icon">{{ getIcon(menu.icon) }}</i>
              <span>{{ menu.menuName }}</span>
            </router-link>
          </template>
        </nav>

        <!-- 侧边栏底部 - 用户信息 -->
        <div class="sidebar-footer">
          <div class="user-info">
            <div class="user-avatar">
              <i class="icon">👤</i>
            </div>
            <div class="user-details">
              <div class="user-name">{{ username || '未登录' }}</div>
            </div>
          </div>
          <button class="logout-btn" @click="handleLogout">
            <i class="icon">🚪</i>
            <span>退出登录</span>
          </button>
        </div>
      </aside>

      <!-- 主内容区 -->
      <main class="app-main">
        <router-view />
      </main>
    </template>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { getUserMenus, clearDynamicRoutes } from './router'
import toast from './utils/toast'

const router = useRouter()
const route = useRoute()
const username = ref('')
const userMenus = ref([])
const isMobileMenuOpen = ref(false)

// 图标映射表
const iconMap = {
  'article': '📝',
  'me': '👤',
  'user': '👥',
  'article-admin': '📝',
  'user-admin': '👥',
  'setting': '⚙️',
  'profile': '👤',
  'my-articles': '📄',
  'article-management': '📝',
  'user-management': '👥'
}

// 获取图标
const getIcon = (iconName) => {
  return iconMap[iconName] || '📄'
}

// 判断是否是登录页或注册页
const isLoginPage = computed(() => {
  return route.path === '/login' || route.path === '/' || route.path === '/register'
})

// 获取用户信息和菜单
const loadUserData = () => {
  username.value = localStorage.getItem('username') || ''
  userMenus.value = getUserMenus()
  // 调试：打印菜单数据
  console.log('加载的菜单数据:', userMenus.value)
  if (userMenus.value.length > 0) {
    console.log('第一个菜单:', userMenus.value[0])
    console.log('第一个菜单的icon字段:', userMenus.value[0].icon)
    console.log('第一个菜单的meta:', userMenus.value[0].meta)
  }
}

onMounted(() => {
  loadUserData()
  
  // 页面加载时恢复动态路由
  const accessToken = localStorage.getItem('accessToken')
  if (accessToken) {
    const menus = getUserMenus()
    if (menus && menus.length > 0) {
      console.log('App.vue: 页面加载，恢复动态路由')
      import('./router').then(({ restoreDynamicRoutes }) => {
        restoreDynamicRoutes()
      })
    }
  }
})

// 切换移动端菜单
const toggleMobileMenu = () => {
  isMobileMenuOpen.value = !isMobileMenuOpen.value
}

// 关闭移动端菜单
const closeMobileMenu = () => {
  isMobileMenuOpen.value = false
}

// 监听路由变化，更新菜单并关闭移动端菜单
watch(() => route.path, () => {
  closeMobileMenu()
  loadUserData()
})

const handleLogout = () => {
  if (confirm('确定要退出登录吗？')) {
    // 保存"记住我"相关信息（不要删除）
    const rememberMe = localStorage.getItem('rememberMe')
    const savedUsername = localStorage.getItem('savedUsername')
    const savedPassword = localStorage.getItem('savedPassword')
    
    // 清除登录信息
    localStorage.removeItem('isLoggedIn')
    localStorage.removeItem('accessToken')
    localStorage.removeItem('refreshToken')
    localStorage.removeItem('username')
    localStorage.removeItem('userInfo')
    
    // 恢复"记住我"相关信息
    if (rememberMe === 'true') {
      localStorage.setItem('rememberMe', rememberMe)
      if (savedUsername) localStorage.setItem('savedUsername', savedUsername)
      if (savedPassword) localStorage.setItem('savedPassword', savedPassword)
    }
    
    // 清除动态路由和会话数据
    clearDynamicRoutes()
    
    toast.success('已退出登录')
    
    // 关闭移动端菜单
    closeMobileMenu()
    
    // 跳转到登录页
    router.push('/login')
  }
}
</script>

<style>
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
  background: #f8f9fa;
}

.app-container {
  display: flex;
  min-height: 100vh;
  width: 100%;
}

/* 登录页面全屏显示 */
.app-container.login-layout {
  display: block;
  height: auto;
  min-height: 100vh;
  overflow-y: auto;
}

/* 侧边栏样式 */
.app-sidebar {
  width: 260px;
  background: linear-gradient(180deg, #667eea 0%, #764ba2 100%);
  color: white;
  display: flex;
  flex-direction: column;
  box-shadow: 4px 0 12px rgba(0, 0, 0, 0.1);
  flex-shrink: 0;
}

.sidebar-header {
  padding: 30px 20px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.logo {
  font-size: 1.5rem;
  font-weight: 700;
  color: white;
  display: flex;
  align-items: center;
  gap: 12px;
  margin: 0;
}

.icon {
  font-style: normal;
}

/* 导航菜单 */
.sidebar-nav {
  flex: 1;
  padding: 20px 0;
  overflow-y: auto;
}

.nav-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 15px 25px;
  color: rgba(255, 255, 255, 0.8);
  text-decoration: none;
  font-size: 15px;
  font-weight: 500;
  transition: all 0.3s;
  cursor: pointer;
  border-left: 4px solid transparent;
}

.nav-item:hover {
  background: rgba(255, 255, 255, 0.1);
  color: white;
  border-left-color: white;
}

.nav-item.active {
  background: rgba(255, 255, 255, 0.15);
  color: white;
  border-left-color: white;
}

.nav-item .icon {
  font-size: 20px;
}

.nav-item .badge {
  margin-left: auto;
  padding: 2px 8px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  font-size: 11px;
  font-weight: 600;
}

.logout-btn {
  width: 100%;
  margin-top: 15px;
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.1);
  border: 2px solid rgba(255, 255, 255, 0.2);
  border-radius: 10px;
  color: white;
  font-size: 14px;
  font-weight: 600;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10px;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
}

.logout-btn::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  width: 0;
  height: 0;
  border-radius: 50%;
  background: rgba(255, 100, 100, 0.3);
  transform: translate(-50%, -50%);
  transition: width 0.6s, height 0.6s;
}

.logout-btn:hover::before {
  width: 300px;
  height: 300px;
}

.logout-btn:hover {
  background: rgba(255, 100, 100, 0.25);
  border-color: rgba(255, 107, 107, 0.5);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(255, 107, 107, 0.3);
}

.logout-btn:active {
  transform: translateY(0);
  box-shadow: 0 2px 6px rgba(255, 107, 107, 0.3);
}

.logout-btn .icon {
  font-size: 18px;
  position: relative;
  z-index: 1;
}

.logout-btn span {
  position: relative;
  z-index: 1;
}

/* 侧边栏底部 */
.sidebar-footer {
  padding: 20px;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-avatar {
  width: 45px;
  height: 45px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20px;
}

.user-details {
  flex: 1;
}

.user-name {
  font-weight: 600;
  font-size: 14px;
  margin-bottom: 4px;
}

.user-role {
  font-size: 12px;
  opacity: 0.8;
}

/* 主内容区 */
.app-main {
  flex: 1;
  overflow-y: auto;
  background: #f8f9fa;
}

/* 移动端菜单按钮 */
.mobile-menu-btn {
  display: none;
  position: fixed;
  top: 20px;
  left: 20px;
  z-index: 1001;
  width: 50px;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12px;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
  transition: all 0.3s ease;
}

.mobile-menu-btn:hover {
  transform: scale(1.05);
  box-shadow: 0 6px 16px rgba(102, 126, 234, 0.5);
}

.mobile-menu-btn:active {
  transform: scale(0.95);
}

.hamburger-icon {
  display: flex;
  flex-direction: column;
  gap: 5px;
  align-items: center;
  justify-content: center;
}

.hamburger-icon span {
  display: block;
  width: 22px;
  height: 2.5px;
  background: white;
  border-radius: 2px;
  transition: all 0.3s ease;
}

/* 移动端遮罩层 */
.mobile-overlay {
  display: none;
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 999;
  opacity: 0;
  pointer-events: none;
  transition: opacity 0.3s ease;
}

.mobile-overlay.active {
  opacity: 1;
  pointer-events: auto;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .mobile-menu-btn {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .mobile-overlay {
    display: block;
  }

  .app-sidebar {
    width: 100%;
    max-width: 280px;
    position: fixed;
    left: -100%;
    top: 0;
    bottom: 0;
    z-index: 1000;
    transition: left 0.3s ease;
    box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
  }

  .app-sidebar.mobile-open {
    left: 0;
  }

  .app-main {
    width: 100%;
    padding: 0;
  }

  .sidebar-header {
    padding: 20px 15px;
  }

  .logo {
    font-size: 1.3rem;
  }

  .nav-item {
    padding: 12px 20px;
    font-size: 14px;
  }
}

@media (max-width: 480px) {
  .logo {
    font-size: 1.2rem;
    gap: 8px;
  }

  .nav-item {
    padding: 10px 15px;
    font-size: 13px;
    gap: 10px;
  }

  .nav-item .icon {
    font-size: 18px;
  }
}
</style>
